'use client';

import { createContext, useContext, useState, ReactNode } from 'react';

// 定义全局状态类型
interface GlobalState {
  textBinding: {
    inputText: string;
  };
  counter: {
    count: number;
  };
  list: {
    newItem: string;
    items: string[];
  };
}

// 创建全局状态上下文
const GlobalStateContext = createContext<{
  state: GlobalState;
  updateTextBinding: (inputText: string) => void;
  updateCounter: (count: number) => void;
  updateListNewItem: (newItem: string) => void;
  updateListItems: (items: string[]) => void;
}>({
  state: {
    textBinding: {
      inputText: '',
    },
    counter: {
      count: 0,
    },
    list: {
      newItem: '',
      items: ['项目1', '项目2', '项目3'],
    },
  },
  updateTextBinding: () => {},
  updateCounter: () => {},
  updateListNewItem: () => {},
  updateListItems: () => {},
});

// 全局状态提供者组件
export function GlobalStateProvider({ children }: { children: ReactNode }) {
  const [state, setState] = useState<GlobalState>({
    textBinding: {
      inputText: '',
    },
    counter: {
      count: 0,
    },
    list: {
      newItem: '',
      items: ['项目1', '项目2', '项目3'],
    },
  });

  const updateTextBinding = (inputText: string) => {
    setState(prev => ({
      ...prev,
      textBinding: {
        ...prev.textBinding,
        inputText,
      },
    }));
  };

  const updateCounter = (count: number) => {
    setState(prev => ({
      ...prev,
      counter: {
        ...prev.counter,
        count,
      },
    }));
  };

  const updateListNewItem = (newItem: string) => {
    setState(prev => ({
      ...prev,
      list: {
        ...prev.list,
        newItem,
      },
    }));
  };

  const updateListItems = (items: string[]) => {
    setState(prev => ({
      ...prev,
      list: {
        ...prev.list,
        items,
      },
    }));
  };

  return (
    <GlobalStateContext.Provider
      value={{
        state,
        updateTextBinding,
        updateCounter,
        updateListNewItem,
        updateListItems,
      }}
    >
      {children}
    </GlobalStateContext.Provider>
  );
}

// 自定义Hook用于使用全局状态
export function useGlobalState() {
  const context = useContext(GlobalStateContext);
  if (!context) {
    throw new Error('useGlobalState must be used within a GlobalStateProvider');
  }
  return context;
}